package com.cskaoyan.mall.controller.mall;

import com.cskaoyan.mall.model.sql.Goods;
import com.cskaoyan.mall.model.sql.Result;
import com.cskaoyan.mall.model.sql.Type;
import com.cskaoyan.mall.model.vo.TypeGoodsVO;
import com.cskaoyan.mall.service.GoodsService;
import com.cskaoyan.mall.service.implement.GoodServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/api/mall/goods/*")
public class GoodServlet extends HttpServlet {

    private GoodsService goodsService = new GoodServiceImpl();

    private Gson gson = new Gson();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/mall/goods/", "");
        if("getGoodsByType".equals(action)){
            getGoodsByType(request,response);
        }else if ("searchGoods".equals(action)){
            searchGoods(request,response);
        }
    }

    /**
     *  keyword=408
     * @param request
     * @param response
     */
    private void searchGoods(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String keyword = request.getParameter("keyword");
        List<Goods> goods = goodsService.searchGoods(keyword);
        response.getWriter().println(gson.toJson(Result.ok(goods)));
    }

    /**
     * typeId=-1
     * @param request
     * @param response
     */
    private void getGoodsByType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String typeId = request.getParameter("typeId");
        List<TypeGoodsVO> goodsVOList = goodsService.getGoodsType(typeId);
        response.getWriter().println(gson.toJson(Result.ok(goodsVOList)));
    }

}
